// pages/coupon/index.js
const api =  require('../../utils/api');
const utils = require('../../utils/index');
Page({
  data: {
    storeName: '',
    storeId: 0,
    tabActive: 0,
    tabs: ['账户充值', '团购券', '优惠券', '自助验券'],
    isLoggedIn: true,
    accountBalance: 0,
    rechargeOptions: [],
    rechargeType: 2, // 1: 全国通用充值, 2: 单门店充值
    selectedAmount: 0,
    selectedPackageId: 0,
    isAgreed: true, // 默认同意协议
    groupBuyList: [],
    coupons: [],
    userPoints: 0,
    verifyPlatforms: ['美团', '大众点评', '抖音', '快手', '高德自助验券'],
    showStoreModal: false, // 控制可用门店模态框的显示状态
    showExchangeModal: false, // 控制优惠券兑换确认模态框的显示状态
    showPointsRuleModal: false, // 控制积分使用规则模态框的显示状态
    showRechargeModal: false, // 控制充值须知模态框的显示状态
    showCouponCodeModal: false, // 控制优惠券码模态框的显示状态
    currentCouponId: null, // 当前选中的优惠券ID
    currentCoupon: null, // 当前选中的优惠券对象
    rechargeList: [],
    exchangeableCoupons: [], // 可兑换的优惠券列表
    exchangeLoading: false, // 兑换操作的加载状态
    currentUsageRange: null, // 当前团购券使用范围
    currentCouponCode: "",
    currentRequiredPoints: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 获取本地保存的门店信息
    const storeId = wx.getStorageSync('currentStoreId') || 0;
    const storeName = wx.getStorageSync('currentStoreName') || '';
    
    // 更新数据
    this.setData({
      storeId: storeId,
      storeName: storeName ? `【${storeName}】` : ''
    });
    
    // 检查是否有从其他页面传递过来的标签页索引
    const tabIndex = wx.getStorageSync('couponTabIndex');
    console.log('onLoad:', tabIndex);
    if (tabIndex) {
      this.setData({
        tabActive: tabIndex
      });
    }
    
    // 如果没有门店ID信息，可能需要加载门店信息
    if (!storeId) {
      this.loadDefaultStore();
    } else {
      // 加载充值套餐
      this.loadRechargePackages();
    }
    
    // 获取账户信息
    this.getAccountInfo();
    
    // 获取团购券列表
    this.loadGroupBuyList();

    // 获取用户优惠券列表
    this.loadUserCoupons();
    
    // 获取可兑换的优惠券列表
    this.loadExchangeableCoupons();
  },

  // 获取账户信息
  getAccountInfo: function() {
    wx.showLoading({
      title: '加载中...',
    });
    
    api.user.getAccountInfo()
      .then(res => {
        if (res && res.success && res.data) {
          this.setData({
            accountBalance: res.data.balance || 0,
            userPoints: res.data.points || 0
          });
        } else {
          wx.showToast({
            title: '获取账户信息失败',
            icon: 'none'
          });
        }
      })
      .catch(err => {
        console.error('获取账户信息失败:', err);
        wx.showToast({
          title: '获取账户信息失败',
          icon: 'none'
        });
      })
      .finally(() => {
        wx.hideLoading();
      });
  },

  // 加载默认门店信息
  loadDefaultStore: function() {
    wx.showLoading({
      title: '加载门店信息...',
    });
    
    api.store.getHotStores({ page: 1, page_size: 1 })
      .then(res => {
        if (res && res.success && res.data && res.data.list && res.data.list.length > 0) {
          const store = res.data.list[0];
          // 保存门店信息到本地
          wx.setStorageSync('currentStoreId', store.id);
          wx.setStorageSync('currentStoreName', store.name);
          
          // 更新数据
          this.setData({
            storeId: store.id,
            storeName: `【${store.name}】`
          });
          
          // 加载充值套餐
          this.loadRechargePackages();
        } else {
          wx.showToast({
            title: '获取门店信息失败',
            icon: 'none'
          });
        }
      })
      .catch(err => {
        console.error('获取门店信息失败:', err);
        wx.showToast({
          title: '获取门店信息失败',
          icon: 'none'
        });
      })
      .finally(() => {
        wx.hideLoading();
      });
  },

  // 切换标签页
  onTabChange: function (e) {
    const index = parseInt(e.currentTarget.dataset.index);
    this.setData({
      tabActive: index
    });
  },

  // 切换充值类型
  onRechargeTypeChange: function (e) {
    const index = parseInt(e.currentTarget.dataset.index);
    this.setData({
      rechargeType: index,
      selectedAmount: 0,
      selectedPackageId: 0
    });
    
    // 重新加载对应类型的充值套餐
    this.loadRechargePackages();
  },

  // 选择充值金额
  onSelectAmount: function (e) {
    const packageId = parseInt(e.currentTarget.dataset.id);
    const amount = parseFloat(e.currentTarget.dataset.amount);
    this.setData({
      selectedAmount: amount,
      selectedPackageId: packageId
    });
  },

  // 立即充值
  onRecharge: function () {
    // 如果是单门店充值，显示充值须知模态框
    if (this.data.rechargeType === 1) {
      this.setData({
        showRechargeModal: true
      });
    } else {
      // 全国通用充值直接进行充值
      this.doRecharge();
    }
  },
  
  // 切换充值须知模态框显示状态
  toggleRechargeModal: function () {
    this.setData({
      showRechargeModal: !this.data.showRechargeModal
    });
  },
  
  // 确认充值
  confirmRecharge: function () {
    // 关闭模态框
    this.setData({
      showRechargeModal: false
    });
    
    // 执行充值操作
    this.doRecharge();
  },

  // 加载充值套餐
  loadRechargePackages: function() {
    const that = this;
    const type = this.data.rechargeType;
    const storeId = this.data.storeId;
    
    // 如果是单门店充值，但没有门店ID，提示选择门店
    if (type === 2 && storeId <= 0) {
      wx.showToast({
        title: '请先选择门店',
        icon: 'none'
      });
      // 重置套餐数据
      this.setData({
        rechargeOptions: [],
        selectedAmount: 0,
        selectedPackageId: 0
      });
      return;
    }
    
    // 显示加载中
    wx.showLoading({
      title: '加载中...',
    });
    
    // 调用获取充值套餐API
    api.recharge.getPackages({
      type: type,
      store_id: storeId
    })
    .then(res => {
      if (res && res.success && res.data) {
        const packages = res.data.list || [];
        
        // 为套餐数据添加默认值，防止数据异常
        const formattedPackages = packages.map(item => {
          return {
            ...item,
            id: parseInt(item.id) || 0,
            amount: parseFloat(item.amount) || 0,
            gift_amount: parseFloat(item.gift_amount) || 0,
            gift_points: parseInt(item.gift_points) || 0
          };
        });
        
        if (formattedPackages.length > 0) {
          // 更新套餐列表，并默认选中第一个套餐
          that.setData({
            rechargeOptions: formattedPackages,
            selectedAmount: formattedPackages[0].amount,
            selectedPackageId: formattedPackages[0].id
          });
        } else {
          that.setData({
            rechargeOptions: [],
            selectedAmount: 0,
            selectedPackageId: 0
          });
          wx.showToast({
            title: '暂无可用充值套餐',
            icon: 'none'
          });
        }
      } else {
        that.setData({
          rechargeOptions: [],
          selectedAmount: 0,
          selectedPackageId: 0
        });
        wx.showToast({
          title: res.message || '获取充值套餐失败',
          icon: 'none'
        });
      }
    })
    .catch(err => {
      console.error('获取充值套餐失败:', err);
      that.setData({
        rechargeOptions: [],
        selectedAmount: 0,
        selectedPackageId: 0
      });
      wx.showToast({
        title: '获取充值套餐失败',
        icon: 'none'
      });
    })
    .finally(() => {
      wx.hideLoading();
    });
  },

  // 执行充值操作
  doRecharge: function () {
    const that = this;
    const packageId = this.data.selectedPackageId;
    const amount = this.data.selectedAmount;
    const type = this.data.rechargeType;
    const storeId = this.data.storeId;
    
    if (packageId <= 0 || amount <= 0) {
      wx.showToast({
        title: '请选择充值套餐',
        icon: 'none'
      });
      return;
    }
    
    // 显示加载中
    wx.showLoading({
      title: '处理中...',
    });
    
    // 调用创建充值订单API
    api.member.recharge.create({
      package_id: packageId,
      amount: parseFloat(amount),
      type: type,
      store_id: storeId
    })
    .then(res => {
      if (res && res.success && res.data) {
        // 创建订单成功，调用支付
        const payParams = res.data.pay_params;
        
        // 调用微信支付
        wx.requestPayment({
          timeStamp: payParams.time_stamp,
          nonceStr: payParams.nonce_str,
          package: payParams.package,
          signType: payParams.sign_type,
          paySign: payParams.pay_sign,
          success: function (payRes) {
            // 支付成功
            wx.showToast({
              title: '充值成功',
              icon: 'success'
            });
            
            // 更新账户余额
            that.setData({
              accountBalance: that.data.accountBalance + amount
            });
            
            // 刷新充值记录
            that.getRechargeList();
          },
          fail: function (err) {
            console.error('支付失败:', err);
            wx.showToast({
              title: '支付失败',
              icon: 'none'
            });
          }
        });
      } else {
        wx.showToast({
          title: res.message || '创建订单失败',
          icon: 'none'
        });
      }
    })
    .catch(err => {
      console.error('创建订单失败:', err);
      wx.showToast({
        title: '创建订单失败',
        icon: 'none'
      });
    })
    .finally(() => {
      wx.hideLoading();
    });
  },

  // 获取充值记录列表
  getRechargeList: function () {
    const that = this;
    
    api.member.recharge.list({
      page: 1,
      page_size: 10
    })
    .then(res => {
      if (res && res.success) {
        // 更新充值记录列表
        that.setData({
          rechargeList: res.data.list
        });
      }
    })
    .catch(err => {
      console.error('获取充值记录失败:', err);
    });
  },

  // 去购买团购券
  onBuyGroupon: function (e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/coupon/buy?id=${id}`
    });
  },

  // 获取用户优惠券列表
  loadUserCoupons: function() {
    wx.showLoading({
      title: '加载中',
    });
    api.coupon.getMyCoupons().then(res => {
      console.log("getMyCoupons:",res);
      wx.hideLoading();
      if (res.success) {
        // 添加券码属性确保不为空并格式化时间
        const now = Math.floor(Date.now() / 1000); // 当前时间戳（秒）
        const coupons = res.data.map(item => {
          // 检查优惠券是否过期
          const isExpired = now > item.valid_until;
          return {
            ...item,
            code: item.code || `CP${new Date().getTime()}${Math.floor(Math.random() * 1000)}`,
            valid_from: utils.formatTimestamp(item.valid_from),
            valid_until: utils.formatTimestamp(item.valid_until),
            start_time: utils.formatTimestamp(item.start_time),
            end_time: utils.formatTimestamp(item.end_time),
            is_expired: isExpired // 添加过期标志
          };
        });
        this.setData({
          coupons: coupons
        });
      } else {
        wx.showToast({
          title: res.message || '获取优惠券失败',
          icon: 'none'
        });
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: '网络错误',
        icon: 'none'
      });
      console.error('获取优惠券失败:', err);
    });
  },
  
  // 获取可兑换优惠券列表
  loadExchangeableCoupons: function() {
    wx.showLoading({
      title: '加载中',
    });
    api.coupon.getExchangeableCoupons().then(res => {
      wx.hideLoading();
      if (res.success) {
        // 格式化时间
        const list = (res.data.list || []).map(item => {
          return {
            ...item,
            start_time: utils.formatTimestamp(item.start_time),
            end_time: utils.formatTimestamp(item.end_time)
          };
        });
        this.setData({
          exchangeableCoupons: list,
          userPoints: res.data.member_points || 0
        });
      } else {
        wx.showToast({
          title: res.message || '获取可兑换优惠券失败',
          icon: 'none'
        });
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: '网络错误',
        icon: 'none'
      });
      console.error('获取可兑换优惠券失败', err);
    });
  },
  
  // 兑换优惠券
  onExchangeCoupon: function (e) {
    const id = e.currentTarget.dataset.id;
    const requiredPoints = e.currentTarget.dataset.points;
    
    // 保存当前选中的优惠券ID并显示确认模态框
    this.setData({
      currentCouponId: id,
      currentRequiredPoints: requiredPoints,
      showExchangeModal: true
    });
  },
  
  // 切换优惠券兑换确认模态框显示状态
  toggleExchangeModal: function () {
    this.setData({
      showExchangeModal: !this.data.showExchangeModal
    });
  },
  
  // 确认兑换优惠券
  confirmExchange: function () {
    const couponId = this.data.currentCouponId;
    // 关闭模态框
    this.setData({
      showExchangeModal: false,
      exchangeLoading: true
    });
    
    // 调用兑换接口
    api.coupon.exchangeCoupon(couponId).then(res => {
      if (res.success) {
        wx.showToast({
          title: '兑换成功',
          icon: 'success'
        });
        
        // 更新用户积分和优惠券列表
        this.setData({
          userPoints: res.data.points_remain || this.data.userPoints
        });
        
        // 重新加载优惠券列表和可兑换优惠券列表
        this.loadUserCoupons();
        this.loadExchangeableCoupons();
      } else {
        wx.showToast({
          title: res.message || '兑换失败',
          icon: 'none'
        });
      }
    }).catch(err => {
      console.error('兑换优惠券失败:', err);
      wx.showToast({
        title: '网络错误',
        icon: 'none'
      });
    }).finally(() => {
      this.setData({
        exchangeLoading: false
      });
    });
  },

  // 验证兑换码
  onVerifyCode: function () {
    wx.showToast({
      title: '验证功能暂未开放',
      icon: 'none'
    });
  },

  // 扫码
  onTapScan: function () {
    const that = this;
    wx.scanCode({
      success: function (res) {
        that.setData({
          couponCode: res.result
        });
      },
      fail: function () {
        wx.showToast({
          title: '扫码失败',
          icon: 'none'
        });
      }
    });
  },

  // 切换团购券使用规则显示状态
  toggleRules: function (e) {
    const id = e.currentTarget.dataset.id;
    const list = this.data.groupBuyList;
    const updatedList = list.map(item => {
      if (item.id === id) {
        return { ...item, showRules: !item.showRules };
      }
      return item;
    });
    
    this.setData({
      groupBuyList: updatedList
    });
  },

  // 切换可用门店模态框显示状态
  toggleStoreModal: function (e) {
    const store = e.currentTarget.dataset.store;
    const groupBuyId = e.currentTarget.dataset.id;
    
    // 先切换弹窗状态
    this.setData({
      showStoreModal: !this.data.showStoreModal
    });
    
    // 如果是打开弹窗并且有ID，获取使用范围数据
    if (this.data.showStoreModal && groupBuyId) {
      this.getGroupBuyUsageRange(groupBuyId);
    }
  },

  // 获取团购券使用范围
  getGroupBuyUsageRange: function(id) {
    wx.showLoading({
      title: '加载中...'
    });
    
    api.groupBuy.getUsageRange(id)
      .then(res => {
        if (res && res.success && res.data) {
          this.setData({
            currentUsageRange: res.data
          });
        } else {
          console.error('获取团购券使用范围失败:', res);
          wx.showToast({
            title: '获取使用范围失败',
            icon: 'none'
          });
        }
      })
      .catch(err => {
        console.error('获取团购券使用范围失败:', err);
        wx.showToast({
          title: '获取使用范围失败',
          icon: 'none'
        });
      })
      .finally(() => {
        wx.hideLoading();
      });
  },

  // 切换积分使用规则模态框显示状态
  togglePointsRuleModal: function () {
    this.setData({
      showPointsRuleModal: !this.data.showPointsRuleModal
    });
  },

  // 查看积分明细
  onViewPointsDetail: function() {
    wx.navigateTo({
      url: '/pages/coupon/points'
    });
  },

  // 查看余额明细
  onViewBalanceDetail: function() {
    wx.navigateTo({
      url: '/pages/coupon/balance-detail'
    });
  },

  // 切换协议同意状态
  toggleAgreement: function () {
    this.setData({
      isAgreed: !this.data.isAgreed
    });
  },

  // 选择门店
  selectStore: function() {
    wx.reLaunch({
      url: '/pages/index/index',
      fail: (e) => {
        console.error(e);
      }
    });
  },

  // 获取团购券列表
  loadGroupBuyList: function() {
    api.groupBuy.getList({
      page: 1,
      pageSize: 50,
      storeId: wx.getStorageSync('currentStoreId')
    })
      .then(res => {
        if (res && res.success && res.data && res.data.list) {
          const list = res.data.list.map(item => {
            const validDays = Math.floor((item.end_time - item.start_time) / (60 * 60 * 24));
            return {
              ...item,
              original_price: (item.original_price / 100).toFixed(2),
              group_price: (item.group_price / 100).toFixed(2),
              validDays: validDays,
              startTimeStr: utils.formatTimestamp(item.start_time),
              endTimeStr: utils.formatTimestamp(item.end_time)
            };
          });
          this.setData({
            groupBuyList: list
          });
        } else {
          console.error('获取团购券失败:', res);
          this.setData({
            groupBuyList: []
          });
        }
      })
      .catch(err => {
        console.error('获取团购券失败:', err);
        this.setData({
          groupBuyList: []
        });
      });
  },

  // 显示优惠券码
  showCouponCode: function(e) {
    const id = e.currentTarget.dataset.id;
    const coupons = this.data.coupons;
    const coupon = coupons.find(item => item.id === id);
    
    if (coupon) {
      this.setData({
        currentCoupon: coupon,
        showCouponCodeModal: true
      });
    }
  },
  
  // 关闭优惠券码模态框
  closeCouponCodeModal: function() {
    this.setData({
      showCouponCodeModal: false
    });
  },
  
  // 复制优惠券码到剪贴板
  copyCouponCode: function() {
    const code = this.data.currentCoupon.code;
    wx.setClipboardData({
      data: code,
      success: function() {
        wx.showToast({
          title: '复制成功',
          icon: 'success'
        });
      }
    });
  },
});